package util;

import java.io.Closeable;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

/**
 * Utility methods for {@link Disposable} entities.
 * 
 * @author Mykhaylo Adamovych
 */
public class DisposableUtils {
    public static final String ERROR_WHILE_CLEANING_RESOURCES = "Error while cleaning resources.";
    public static final Logger log = Logger.getLogger(DisposableUtils.class);
    
    public static final void dispose(Disposable disposable) {
        if (disposable == null)
            return;
        try {
            disposable.dispose();
        } catch (Exception e) {
            throw new Error(e);
        }
    }
    
    public static final void disposeQuietly(Disposable disposable) {
        if (disposable == null)
            return;
        try {
            disposable.dispose();
        } catch (Exception e) {
            log.error(ERROR_WHILE_CLEANING_RESOURCES, e);
        }
    }
    
    public static final void closeQuietly(Connection disposable) {
        if (disposable == null)
            return;
        try {
            disposable.close();
        } catch (SQLException e) {
            log.error(ERROR_WHILE_CLEANING_RESOURCES, e);
        }
    }
    
    public static final void closeQuietly(PrintStream disposable) {
        if (disposable == null)
            return;
        disposable.close();
    }
    
    public static final void closeQuietly(ResultSet disposable) {
        if (disposable == null)
            return;
        try {
            disposable.close();
        } catch (SQLException e) {
            log.error(ERROR_WHILE_CLEANING_RESOURCES, e);
        }
    }
    
    public static final void closeQuietly(Statement disposable) {
        if (disposable == null)
            return;
        try {
            disposable.close();
        } catch (SQLException e) {
            log.error(ERROR_WHILE_CLEANING_RESOURCES, e);
        }
    }
    
    public static final void closeQuietly(Closeable closeable) {
        if (closeable == null)
            return;
        try {
            closeable.close();
        } catch (IOException e) {
            log.error(ERROR_WHILE_CLEANING_RESOURCES, e);
        }
    }
    
    public static final void closeQuietly(EntityManager closeable) {
        if (closeable == null)
            return;
        if (closeable.getTransaction().isActive())
            closeable.getTransaction().rollback();
        closeable.close();
    }
}
